package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.Employee;
import cn.itsource.hrm.domain.Tenant;
import cn.itsource.hrm.mapper.EmployeeMapper;
import cn.itsource.hrm.mapper.TenantMapper;
import cn.itsource.hrm.query.TenantQuery;
import cn.itsource.hrm.service.ITenantService;
import cn.itsource.hrm.util.LetterUtil;
import cn.itsource.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.bouncycastle.math.ec.custom.sec.SecT113Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yhptest
 * @since 2020-06-22
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        //分页
        Page<Tenant> page = new Page<>(query.getPage(),query.getRows());
        //只要传了Page对象，会自动做分页，query做高级查询
        List<Tenant> datas = tenantMapper.loadPageList(page,query);
        if (page.getTotal()<1)
            return new PageList<>();
        return new PageList<>(page.getTotal(),datas);
    }

    @Override
    public Map<String, Object> getLetters() {
        Map<String,Object> result = new HashMap<>();
        //机构
        List<Tenant> tenants = tenantMapper.selectList(null);
        result.put("tenants",tenants);
        //首字母
        TreeSet<String> letters = new TreeSet<>();
        for (Tenant tenant : tenants) {
            String firstLetter = LetterUtil.getFirstLetter(tenant.getCompanyName());
            letters.add(firstLetter.toUpperCase());
        }
        result.put("letters",letters);

        return result;
    }

    public TenantServiceImpl() {
        super();
    }

    @Override
    public boolean insert(Tenant entity) {

        //添加机构-默认已经返回了id
        entity.setRegisterTime(new Date());
        tenantMapper.insert(entity);
        //添加机构管理员
        Employee admin = entity.getAdmin();
        admin.setRealName(admin.getUsername());
        admin.setInputTime(new Date());
        admin.setState(0);
        admin.setType(3);
        admin.setTenantId(entity.getId());
        employeeMapper.insert(admin);
        return true;
    }

    @Override
    public boolean deleteById(Serializable id) {

        //删除机构
        tenantMapper.deleteById(id);
        //删除机构管理员
        employeeMapper.removeByTenantId(id);

        return true;
    }

    @Override
    public boolean updateById(Tenant entity) {

        //修改机构
        tenantMapper.updateById(entity);
        //修改机构管理员
        entity.getAdmin().setTenantId(entity.getId());
        employeeMapper.updateById(entity.getAdmin());
        return true;
    }
}
